package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/1 15:06
 * @Description:登录
 */
@RestController
@RequestMapping("/login")
public class LoginController {

	@Autowired
	JedisPool jedisPool;

	@Reference
	MemberService memberService;

	@RequestMapping("/check")
	public Result check(HttpServletResponse response, @RequestBody Map map) {
		//校验验证码
		// toString()   String.valueOf  (String)
		String validateCode = String.valueOf(map.get("validateCode"));
		String telephone = String.valueOf(map.get("telephone"));
		String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
		if(codeInRedis == null || !validateCode.equals(codeInRedis)){
			return new Result(false, MessageConstant.VALIDATECODE_ERROR);
		}
		//判断是不是会员，如果不是，自动注册成为会员
		Member member=memberService.findByTelephone(telephone);
		if(member == null){
			member = new Member();
			member.setRegTime(new Date());
			member.setPhoneNumber(telephone);
			memberService.add(member);
		}
		//将用户的手机号存入cookie，后期会根据cookie传过来的手机号查询redis，从而获取用户信息
        Cookie cookie = new Cookie("login_member_telephone",telephone);
		cookie.setPath("/");
		cookie.setMaxAge(60*60*24*30);
		response.addCookie(cookie);
	  return new Result(true,MessageConstant.LOGIN_SUCCESS);
	}
}
